package com.hrpc.loadbalancer.impl;

import com.hrpc.exceptions.LoadBalancerException;
import com.hrpc.hRpcBootStarp;
import com.hrpc.loadbalancer.AbstractLoadBalancer;
import com.hrpc.loadbalancer.Selector;
import io.netty.channel.Channel;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 最短响应时间的负载均衡策略
 */
public class MinimumResponseTime extends AbstractLoadBalancer {
    @Override
    protected Selector getSelector(List<InetSocketAddress> serviceList) {
        return new MinimumResponseTimeSelector();
    }
    private static class MinimumResponseTimeSelector implements Selector{

        public MinimumResponseTimeSelector() {

        }

        @Override
        public InetSocketAddress getNext() {
            Map.Entry<Long, Channel> entry = hRpcBootStarp.ANSWER_TIME_CHANNEL_CACHE.firstEntry();
            if (entry != null){
                SocketAddress socketAddress = entry.getValue().remoteAddress();
                return (InetSocketAddress) socketAddress;
            }
            //直接从缓存中获取一个可用的
            Channel channel = (Channel) hRpcBootStarp.CHANNEL_CACHE.values().toArray()[0];
            return (InetSocketAddress) channel.remoteAddress();
        }


    }
}
